package com.dmzapp.api.servlet;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.dmzapp.api.cache.local.LocalCache;
import com.dmzapp.api.cache.redis.RedisClient;
import com.dmzapp.api.db.AppDao;
import com.dmzapp.api.util.Constant;
import com.dmzapp.api.util.StringUtils;
import com.dmzapp.api.vo.AppInfo;
import com.dmzapp.api.vo.DmzEnv;

/**
 * 
 * 根据条件获取applist Servlet implementation class for Servlet: AppListRequestHandler
 * 
 */
public class AppFilterHandler extends DMZSerlvet implements javax.servlet.Servlet {
    static final long serialVersionUID = 1L;
    Logger logger = LoggerFactory.getLogger("dmzlog");
    private ObjectMapper mapper = new ObjectMapper();

    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response) {
        try {
            String version = request.getParameter("v_code");
            String username = (String) request.getAttribute("u");
            int clientVersionCode = 0;
            if (version != null) {
                clientVersionCode = Integer.valueOf(version);
            }
            int start = Integer.valueOf(request.getParameter("start"));

            Map<String, Object> responseMap = new HashMap<String, Object>();

            Collection<String> installedPackages = RedisClient.getInstance().checkInstallpackagesExist(username);
            
            // packages 不存在，有可能是缓存中没有该用户的数据，再去数据库中获取一把
            if (installedPackages == null || installedPackages.isEmpty()) {
                installedPackages = AppDao.getInstance().getInstallPackalistByusername(username);
                if (installedPackages != null) {
                    RedisClient.getInstance().setInstallpackages(username, installedPackages);
                }
            }
            // 3 通过appid set，获取本地的app信息
            List<AppInfo> appListResponse = new ArrayList<AppInfo>();
            for (AppInfo app : LocalCache.getInstance().appCache.values()) {
                AppInfo newapp = new AppInfo(app, clientVersionCode);

                if ((clientVersionCode < 5 && newapp.getCustom_active() == 1)
                        || (installedPackages == null || installedPackages.contains(app.getPackagename()))) {
                    // 如果是低版本，则不会将需要注册的app传过去
                } else {
                    appListResponse.add(newapp);
                }
            }
            logger.debug("nofity app list: " + (appListResponse == null ? null : appListResponse.size()));

            responseMap.put("applist", appListResponse);
            responseMap.put("dmzenv", new DmzEnv());
            responseMap.put("listSize", appListResponse.size());
            responseMap.put("server_time", Calendar.getInstance().getTimeInMillis());

            mapper.writeValue(response.getWriter(), responseMap);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }
    }
}